package com.leyou.page.service;

import com.leyou.item.pojo.*;
import com.leyou.page.client.BrandClient;
import com.leyou.page.client.CategoryClient;
import com.leyou.page.client.GoodsClient;
import com.leyou.page.client.SpecificationClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.persistence.Id;
import java.io.File;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author huangxin
 * @date 2019/5/7-18:36
 */
@Service
@Slf4j
public class PageService {
    @Autowired
    private CategoryClient categoryClient;
    @Autowired
    private BrandClient brandClient;
    @Autowired
    private GoodsClient goodsClient;
    @Autowired
    private SpecificationClient specificationClient;
    @Autowired
    TemplateEngine templateEngine;

    public Map<String, Object>      loadModel(Long spuId) {
        Map<String, Object> model = new HashMap<>();
        //spu
        Spu spu = goodsClient.querySpuById(spuId);
        //skus
        List<Sku> skus = spu.getSkus();
        //detail
        SpuDetail detail = spu.getSpuDetail();
        //categories
        List<Category> categories = categoryClient.queryCategoryByIds(Arrays.asList(spu.getCid1(), spu.getCid2(), spu.getCid3()));
        //brand
        Brand brand = brandClient.queryBrandByid(spu.getBrandId());
        //specs
        List<SpecGroup> specs = specificationClient.queryGroupByCid(spu.getCid3());

        model.put("title", spu.getTitle());
        model.put("subTitle", spu.getSubTitle());
        model.put("skus", skus);
        model.put("detail", detail);
        model.put("categories", categories);
        model.put("brand", brand);
        model.put("specGroups", specs);

        return model;
    }

    public void createHtml(Long spuId) {
        //生成html
        //上下文
        Context context = new Context();
        context.setVariables(loadModel(spuId));
        //输出流
        File dest = new File("D:/nginx-1.10.3/html/item", spuId + ".html");
        //先删除
        if (dest.exists()){
            dest.delete();
        }
        //创建文件夹
        if (dest.getParentFile().isDirectory() && !dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }

        try (PrintWriter writer = new PrintWriter(dest)) {
            //生成
            templateEngine.process("item", context, writer);
        } catch (Exception e) {
            log.error("[静态页服务]生成静态页异常！   " + e);
        }
    }

    /**
     * 删除页面
     * @param spuId
     */
    public void deleteHtml(Long spuId) {
        File dest = new File("D:/nginx-1.10.3/html/item", spuId + ".html");
        if (dest.exists()){
            dest.delete();
        }
    }
}
